#!/bin/bash

# 部署脚本
set -e

echo "🚀 开始部署 YanXue AI Go..."

# 配置变量
ENVIRONMENT=${1:-staging}
VERSION=${2:-latest}
REGISTRY="ghcr.io/yourusername/yanxue_ai_go"

echo "📋 部署信息:"
echo "  环境: $ENVIRONMENT"
echo "  版本: $VERSION"
echo "  镜像仓库: $REGISTRY"

# 检查Docker和Docker Compose
if ! command -v docker &> /dev/null; then
    echo "❌ Docker 未安装"
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose 未安装"
    exit 1
fi

# 创建环境配置
if [ ! -f ".env" ]; then
    echo "📄 创建环境配置文件..."
    cp .env.example .env
    echo "⚠️  请编辑 .env 文件配置必要的环境变量"
fi

# 拉取最新镜像
echo "📥 拉取最新镜像..."
services=("gateway" "agent" "mcp" "rag")
for service in "${services[@]}"; do
    echo "  拉取 $service:$VERSION..."
    docker pull $REGISTRY/$service:$VERSION || echo "⚠️  镜像 $service:$VERSION 不存在，将使用本地构建"
done

# 停止现有服务
echo "🛑 停止现有服务..."
docker-compose down

# 启动基础设施服务
echo "🔧 启动基础设施服务..."
docker-compose up -d postgres redis mongodb elasticsearch milvus

# 等待服务就绪
echo "⏳ 等待数据库服务就绪..."
sleep 30

# 运行数据库迁移
echo "📊 运行数据库迁移..."
docker-compose run --rm gateway go run cmd/migrate/main.go up || echo "⚠️  迁移失败，请检查数据库连接"

# 启动应用服务
echo "🚀 启动应用服务..."
docker-compose up -d gateway agent mcp rag

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 20

# 健康检查
echo "🔍 服务健康检查..."
services_health=()

check_service() {
    local service=$1
    local port=$2
    local name=$3
    
    if curl -f -s "http://localhost:$port/health" > /dev/null; then
        echo "  ✅ $name 服务正常"
        services_health+=("$name: ✅")
    else
        echo "  ❌ $name 服务异常"
        services_health+=("$name: ❌")
    fi
}

check_service "gateway" "8080" "网关"
check_service "agent" "8081" "Agent"
check_service "mcp" "8082" "MCP"
check_service "rag" "8083" "RAG"

# 显示服务状态
echo ""
echo "📊 服务状态汇总:"
for status in "${services_health[@]}"; do
    echo "  $status"
done

# 显示访问信息
echo ""
echo "🌐 服务访问地址:"
echo "  API网关: http://localhost:8080"
echo "  Agent服务: http://localhost:8081"
echo "  MCP服务: http://localhost:8082"
echo "  RAG服务: http://localhost:8083"
echo "  Grafana监控: http://localhost:3000 (admin/admin)"
echo "  Prometheus: http://localhost:9090"
echo "  Jaeger追踪: http://localhost:16686"

# 显示有用的命令
echo ""
echo "📝 常用命令:"
echo "  查看日志: docker-compose logs -f [service_name]"
echo "  重启服务: docker-compose restart [service_name]"
echo "  停止所有: docker-compose down"
echo "  查看状态: docker-compose ps"

echo ""
echo "🎉 部署完成！"